<template>
<div class="">
    <j-modal
      width="80%"
      :title="title"
      :visible.sync="editModalVisible"
      :fullscreen.sync="fullscreen"
      :switch-fullscreen="switchFullscreen"
      @cancel="handleCancleDbSync"
      :destroyOnClose="true"
    >
      <template slot="footer">
        <a-button @click="handleCancleDbSync">
          关闭
        </a-button>
        <a-button type="primary" :loading="syncLoading" @click="handleDbSync" >确定</a-button>
      </template>
      <div class="table-page-search-wrapper warp">
        <a-form-model layout="inline" ref="ruleForm" :model="formData" :rules="rules">
          <a-row :gutter="24">
            <a-col :xl="8" :lg="8" :md="8" :sm="24">
              <a-form-model-item label="组合报表名称" prop="templetName">
                <a-input v-model="formData.templetName" placeholder="请输入报表名称"/>
              </a-form-model-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="8" :sm="24">
              <a-form-model-item label="组合报表编码" prop="templetCode">
                <a-input v-model="formData.templetCode"  placeholder="请输入报表编码"/>
              </a-form-model-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="8" :sm="24">
              <a-form-model-item label="组合报表风格" prop="templetStyle">
                <j-dict-select-tag v-model="formData.templetStyle" placeholder="请选择报表" dict-code="online_graph_display_template"/>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
        <a-tabs defaultActiveKey="1">
          <a-tab-pane key="1" tab="图表配置" forceRender>
            <!-- 操作按钮区域 -->
            <div class="table-operator">
              <a-button type="primary" icon="plus" @click="handleAddGraphRepoart">新增</a-button>
              <a-popconfirm v-if="selectedRowKeys.length" :title="'确定要删除这'+selectedRowKeys.length+'项吗?'" @confirm="() => handleRemoveGraphRepoart()">
                <a-button icon="minus" >删除</a-button>
              </a-popconfirm>
            </div>
            <a-table
              size="middle"
              bordered
              :rowKey="(record, index) => index"
              :columns="columns"
              :data-source="formData.diagramCombinationDetails"
              :pagination="false"
              :row-selection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
            >
              <div slot="graphreportName" slot-scope="text, record ">
                <a-select
                  v-model="record['graphreportCode']"
                  :options="graphreportNames"
                  allowClear
                  style="margin: -5px 0"
                  show-search
                  :filter-option="filterOption"
                ></a-select>
              </div>
              <div slot="graphreportType" slot-scope="text, record">
                <a-select v-model="record['graphreportType']" >
                  <a-select-option v-for="(item,i) in graphTypeDictOptions" :key="i" :value="item.value">{{item.text}}</a-select-option>
                </a-select>
              </div>
              <div slot="groupNum" slot-scope="text, record,index">
                <a-input
                  type="number"
                  style="margin: -5px 0"
                  :value="text"
                  v-model="record['groupNum']"
                  @change="groupNumChange(record,index)"
                />
              </div>
              <div slot="groupTxt" slot-scope="text, record">
                <a-input
                  style="margin: -5px 0"
                  :value="text"
                  v-model="record['groupTxt']"
                  @change="combinationChange('groupTxt',record['groupTxt'],record['groupNum'])"
                />
              </div>
              <div slot="groupStyle" slot-scope="text, record">
                <a-select style="margin: -5px 0" @change="combinationChange('groupStyle',record['groupStyle'],record['groupNum'])" v-model="record['groupStyle']" allowClear>
                  <a-select-option value="card">卡片</a-select-option>
                  <a-select-option value="tab">标签页</a-select-option>
                  <a-select-option value="grid">栅格</a-select-option>
                  <a-select-option value="combination">组合</a-select-option>
                </a-select>
              </div>
              <div slot="isShow" slot-scope="text, record">
                <a-checkbox :checked="record['isShow']?true:false" @change="checkboxChange(record,'isShow')"  style="margin: -5px 0" ></a-checkbox>
              </div>
              <div slot="templetGrid" slot-scope="text, record">
                <j-input-pop  v-model="record['templetGrid']" @change="combinationChange('templetGrid',record['templetGrid'],record['groupNum'])" style="margin: -5px 0" ></j-input-pop>
              </div>
              <div slot="groupGrid" slot-scope="text, record">
                <j-input-pop  v-model="record['groupGrid']" style="margin: -5px 0" ></j-input-pop>
              </div>
              <div slot="orderNum" slot-scope="text, record">
                <a-input
                  type="number"
                  style="margin: -5px 0"
                  :value="text"
                  v-model="record['orderNum']"
                />
              </div>
            </a-table>
          </a-tab-pane>
          <a-tab-pane key="2" tab="查询配置" forceRender>
            <graphreport-query-config ref="graphreportQueryConfig" :dataSource="formData.diagramCombinationQueryConfigs"></graphreport-query-config>
          </a-tab-pane>
        </a-tabs>
      </div>
    </j-modal>
    </div>
</template>
<script>
import JSelectMultiple from '@/components/jeecg/JSelectMultiple'
import { postAction, putAction, getAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
import JInputPop from '@/components/jeecg/minipop/JInputPop'
import GraphreportQueryConfig from '../components/GraphreportQueryConfig'
import { CHART_LIST } from '../utils/Utils'
export default {
  name: 'onlGraphreportTempletModal',
  components: {
    JSelectMultiple,
    JInputPop,
    GraphreportQueryConfig
  },
  computed: {
    yaxisField: {// y轴字段双向绑定转换
      get: function() {
        return this.formData.yaxisField ? this.formData.yaxisField.split(',') : []
      },
      set: function(value) {
        this.formData.yaxisField = value.join(',')
      }
    }
  },
  data() {
    return {
      editModalVisible: false,
      title: '编辑',
      syncLoading: false,
      fullscreen: true,
      switchFullscreen: true,
      graphreportNames: [], // 自定义图表集合
      selectedRowKeys: [],
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: '4%',
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '图表',
          align: 'center',
          width: '15%',
          dataIndex: 'graphreportName',
          scopedSlots: { customRender: 'graphreportName' }
        },
        {
          title: '图表类型',
          align: 'center',
          width: '12%',
          dataIndex: 'graphreportType',
          scopedSlots: { customRender: 'graphreportType' }
        },
        {
          title: '分组编号',
          align: 'center',
          dataIndex: 'groupNum',
          width: '8%',
          scopedSlots: { customRender: 'groupNum' }
        },
        {
          title: '分组描述',
          align: 'center',
          dataIndex: 'groupTxt',
          width: '12%',
          scopedSlots: { customRender: 'groupTxt' }
        },
        {
          title: '分组展示风格',
          align: 'center',
          dataIndex: 'groupStyle',
          width: '15%',
          scopedSlots: { customRender: 'groupStyle' }
        },
        {
          title: '是否显示',
          align: 'center',
          dataIndex: 'isShow',
          width: '8%',
          scopedSlots: { customRender: 'isShow' }
        },
        {
          title: '组合栅格配置',
          align: 'center',
          dataIndex: 'templetGrid',
          width: '8%',
          scopedSlots: { customRender: 'templetGrid' }
        },
        {
          title: '分组栅格配置',
          align: 'center',
          dataIndex: 'groupGrid',
          width: '8%',
          scopedSlots: { customRender: 'groupGrid' }
        },
        {
          title: '排序',
          align: 'center',
          dataIndex: 'orderNum',
          width: '8%',
          scopedSlots: { customRender: 'orderNum' }
        }
      ],
      url: {
        list: '/online/cgform/head/list',
        edit: '/diagram/diagramCombination/edit',
        add: '/diagram/diagramCombination/add',
        graphreportList: '/diagram/diagramConfiguration/list'
      },
      scopedSlots: [
        { type: 'select', name: 'graphreportName' },
        { type: 'select', name: 'graphreportType' },
        { type: 'number', name: 'groupNum' },
        { type: 'text', name: 'groupTxt' },
        { type: 'select', name: 'groupStyle', dictCode: 'field_type' },
        { type: 'check', name: 'isShow' },
        { type: 'text', name: 'templetGrid' },
        { type: 'text', name: 'groupGrid' },
        { type: 'number', name: 'orderNum' }
      ],
      rules: {
        templetCode: [
          { required: true, message: '请输入组合报表编码', trigger: 'change' },
          { validator: (rule, value, callback) => validateDuplicateValue('cs_diagram_combination', 'templet_code', value, this.formData.id, callback) }
        ],
        templetName: [
          { required: true, message: '请输入组合报表名称', trigger: 'blur' }
        ],
        templetStyle: [
          { required: true, message: '请输入组合报表风格', trigger: 'change' }
        ]
      },
      formData: {
        'createBy': '',
        'createTime': '',
        'id': '',
        'templetCode': '',
        'templetName': '',
        'templetStyle': '',
        'updateBy': '',
        'updateTime': null,
        'diagramCombinationDetails': [],
        'diagramCombinationQueryConfigs': []
      },
      newFormData: {// 新增用数据
        'createBy': '',
        'createTime': '',
        'id': '',
        'templetCode': '',
        'templetName': '',
        'templetStyle': '',
        'updateBy': '',
        'updateTime': null,
        'diagramCombinationDetails': []
      },
      newListFieldData: {
        'createBy': '',
        'createTime': '',
        'graphreportCode': '',
        'graphreportTempletId': '',
        'graphreportType': '',
        'groupNum': '',
        'groupStyle': '',
        'groupTxt': '',
        'id': '',
        'isShow': true,
        'orderNum': '',
        'updateBy': '',
        'updateTime': '',
        'templetGrid': '{"xl":12,"lg":12,"md":12,"sm":12}',
        'groupGrid': '{"xl":12,"lg":12,"md":12,"sm":12}'
      },
      graphTypeDictOptions: CHART_LIST
    }
  },
  created() {
    getAction(this.url.graphreportList, {
      pageSize: 9999
    }).then((res) => {
      if (res.code === 200) {
        const that = this
        res.result.records.forEach(function(item, i) {
          that.graphreportNames.push({
            value: item.code,
            label: item.name
          })
        })
      } else {
        this.$message.error(res.message)
      }
    })
  },
  methods: {
    handleCancleDbSync() { // 关闭
      this.editModalVisible = false
    },
    edit(record) {
      var that = this
      const record_ = JSON.parse(JSON.stringify(record))
      Object.keys(that.formData).forEach(function(key) {
        that.formData[key] = record_[key]
      })
      this.editModalVisible = true
    },
    add() {
      var that = this
      const record_ = JSON.parse(JSON.stringify(that.newFormData))
      Object.keys(that.formData).forEach(function(key) {
        that.formData[key] = record_[key]
      })
      this.editModalVisible = true
    },
    async handleDbSync() { // 弹窗点击确定
      try {
        if (this.$refs.graphreportQueryConfig) {
          const { error, values } = await this.$refs.graphreportQueryConfig.getValuesSync()
          const valid = await this.$refs['ruleForm'].validate()
          if (!error && valid) {
            this.formData.diagramCombinationQueryConfigs = JSON.parse(JSON.stringify(values))
            this.updateData()
          }
        } else {
          const valid = await this.$refs['ruleForm'].validate()
          if (valid) {
            this.updateData()
          }
        }
      } catch (error) {
        console.log(error)
      }
    },
    updateData(params) { // 保存提交数据
      this.syncLoading = true
      if (this.formData.id) {
        putAction(this.url.edit, this.formData).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.editModalVisible = false
            this.$emit('modalFormOk')
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          setTimeout(() => {
            this.syncLoading = false
          }, 60)
        })
      } else {
        postAction(this.url.add, this.formData).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.editModalVisible = false
            this.$emit('modalFormOk')
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          setTimeout(() => {
            this.syncLoading = false
          }, 60)
        })
      }
    },
    handleAddGraphRepoart() { // 新增
      const newData = JSON.parse(JSON.stringify(this.newListFieldData))
      newData.graphreportTempletId = this.formData.id
      const length_ = this.formData.diagramCombinationDetails.length
      if (length_ !== 0) {
        newData.orderNum = this.formData.diagramCombinationDetails[length_ - 1].orderNum + 1
      } else {
        newData.orderNum = 1
      }
      this.formData.diagramCombinationDetails.push(newData)
    },
    handleRemoveGraphRepoart() { // 删除
      var that = this
      this.selectedRowKeys.sort(function(a, b) { return b - a })
      this.selectedRowKeys.forEach(function(index) {
        that.formData.diagramCombinationDetails.splice(index, 1)
      })
      this.selectedRowKeys = []
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    checkboxChange(data, name) {
      if (data[name]) {
        data[name] = 0
      } else {
        data[name] = 1
      }
    },
    combinationChange(key, val, groupNum) { // 值变化 相同图表编号随之改变
      this.formData.diagramCombinationDetails.forEach(element => {
        if (Number(element.groupNum) === Number(groupNum)) {
          element[key] = val
        }
      })
    },
    groupNumChange(record, index) {
      this.formData.diagramCombinationDetails.forEach(function(element, i) {
        if (i !== index && Number(element.groupNum) === Number(record.groupNum)) {
          record['groupStyle'] = element.groupStyle
          record['groupTxt'] = element.groupTxt
        }
      })
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    }
  }
}
</script>
<style>
.warp .ant-select{
  width: 100%;
}
.warp .table-operator{
  margin-bottom: 10px;
}
.ant-card-body .warp {
  padding: 10px;
}
.warp .table-operator .ant-btn{
  margin: 0px 8px 0 0 !important;
}
.ant-card-body .warp .table-operator{
  margin-bottom:10px !important;
}
</style>
